package com.example.forum.services.impl;

import com.example.forum.entity.User;
import com.example.forum.exception.CustomException;
import com.example.forum.mapper.UserMapper;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.example.forum.constant.MessageConstant.*;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册用户
     *
     * @param user
     */
    public void register(User user) throws CustomException {
        // 判断用户是否为空
        if (user == null) {
            throw new CustomException(USER_NULL);
        }
        // 判断用户名是否已存在
        Integer count = userMapper.getByUsername(user.getUsername());
        // 如果存在，则返回错误信息
        if (count > 0) {
            throw new CustomException(USER_EXISTS);
        }
        // 设置属性默认值
        user.setGender(2);
        user.setIsAdmin(0);
        user.setArticleCount(0);
        user.setState(0);
        user.setDeleteState(0);
        // 设置创建时间和更新时间
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        Integer row = userMapper.insert(user);
        if (row != 1) {
            throw new CustomException(USER_REGISTER_FAILED);
        }
        log.info(USER_REGISTER_SUCCESS);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) throws CustomException {
        // 根据用户名查询用户信息
        User user = userMapper.getByUser(username);
        // 判断用户是否存在
        if (user == null) {
            throw new CustomException(USER_NOT_NULL);
        }
        // 获取用户的盐值
        String salt = user.getSalt();
        String md5Salt = MD5Util.md5Salt(password, salt);
        // 比较密码
        if (!user.getPassword().equals(md5Salt)) {
            throw new CustomException(USER_PASSWORD_ERROR);
        }
        return user;
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param id
     * @return
     */
    public User getUser(Long id) throws CustomException {
        User user = userMapper.getUser(id);
        if (user == null) {
            throw new CustomException(USER_NOT_NULL);
        }
        return user;
    }

    /**
     * 更新用户文章数
     *
     * @param userId
     * @return
     */
    public Integer updateArticleCount(Long userId) {
        return userMapper.updateArticleCount(userId);
    }

    /**
     * 修改用户信息
     *
     * @param id
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param phoneNum
     * @param remark
     */
    public void modifyInfo(Long id, String username, String nickname, Integer gender, String email, String phoneNum, String remark) throws CustomException {
        // 判断昵称是否为空
        /*if (nickname == null || StringUtil.isEmpty(nickname)) {
            throw new CustomException(PARAMETER_VERIFICATION_FAILED);
        }*/

        // 判断用户是否存在
        User user = userMapper.getUser(id);
        if (user == null) {
            throw new CustomException(USER_NOT_PERMISSION);
        }

        // 封装新的用户信息
        User newUser = new User();
        newUser.setId(id);
        newUser.setUsername(username);
        newUser.setNickname(nickname);
        newUser.setGender(gender);
        newUser.setEmail(email);
        newUser.setPhoneNum(phoneNum);
        newUser.setRemark(remark);

        Date date = new Date();
        newUser.setUpdateTime(date);

        // 更新用户信息
        Integer row = userMapper.updateByPrimaryKey(newUser);
        if (row != 1) {
            throw new CustomException(SERVER_ERROR);
        }
    }

    /**
     * 修改密码
     *
     * @param user
     * @param oldPwd
     * @param newPwd
     */
    public void modifyPwd(User user, String oldPwd, String newPwd) throws CustomException {
        // 参数校验
        if (StringUtil.isEmpty(oldPwd) || StringUtil.isEmpty(newPwd)) {
            throw new CustomException(PARAMETER_VERIFICATION_FAILED);
        }
        // 获取用户的盐值
        String salt = user.getSalt();

        // 获取用户id, 构建旧密码的MD5值
        Long id = user.getId();
        String md5Salt = MD5Util.md5Salt(oldPwd, salt);

        // 判断旧密码是否正确
        if (!user.getPassword().equals(md5Salt)) {
            throw new CustomException(USER_PASSWORD_ERROR);
        }
        // 生成新的盐值和密码
        String newSalt = UUIDUtil.UUID_32();
        String newMd5Salt = MD5Util.md5Salt(newPwd, newSalt);

        // 封装新的用户信息
        User newUser = new User();
        newUser.setId(id);
        newUser.setSalt(newSalt);
        newUser.setPassword(newMd5Salt);
        newUser.setUpdateTime(new Date());

        Integer row = userMapper.updateByPrimaryKey(newUser);
        // 判断是否更新成功
        if (row != 1) {
            throw new CustomException(SERVER_ERROR);
        }
    }
}
